iT邦幫忙

0

Day 03 | Java 資料型態的轉換

  • 分享至 

  • xImage
  •  

在上一篇學到了java不同的資料型態與變數的使用,這篇則是要學習java資料型態的轉換。


  • 範圍大小的排序:
  1. 浮點數型態皆大於整數型態。
  2. 整數:byte < short < int < long
  3. 浮點數:float < double
  • 基本轉換規則:
  1. 小範圍轉大範圍型態 -> 自動轉換
  2. 大範圍轉小範圍 -> 產生錯誤
  • 強制轉換:
  1. 轉換後可能產生數字失真。
  2. 大範圍轉小範圍:使用(資料型態)強制轉換
    Ex.int n1=3;
    byte n2=(byte)n1; //強制將int轉為byte
  • 字串轉數字(不同型態方式都不同):
  1. 轉成int型態:Integer.parseInt("字串")
    Ex.String s="56";
    int x=Integer/parseInt(s);

2.轉成long型態:Long.parseLong("字串")
Ex.long x=Long.parseLong("55555");

3.轉成float型態:Float.parseFloat("字串")
Ex.float x=Float.parseFloat("3.14");

4.轉成double型態:Double.parseDouble("字串")
Ex.double x=Double.parseDouble("3.1415");

  • 數字轉字串(可用同一種方式完成):
  1. 用String.valueOf(數字)轉成字串。
  2. Ex.int x=3;
    String s1=String.valueOf(x); //把數字3轉成字串

  • 實際演練
  1. 資料型態轉換(小範圍轉大範圍)
    https://ithelp.ithome.com.tw/upload/images/20261006/201843971ClKQ4vDPW.png
  2. 資料型態轉換(大範圍轉小範圍)
    https://ithelp.ithome.com.tw/upload/images/20261006/20184397WztQGcr6qC.png
    ->輸出一樣的數字,沒有改變

若把x的值改成1024,且把int強制轉換成byte時,數字會被影響(因為超過範圍,所以最高位元被除掉了)。
https://ithelp.ithome.com.tw/upload/images/20261006/20184397FAG2da9lkZ.png

浮點數:失去數字精準度。
https://ithelp.ithome.com.tw/upload/images/20261007/20184397cZJBILSA4V.png

  1. 字串轉數字
    https://ithelp.ithome.com.tw/upload/images/20261007/20184397K4BFyF5RDG.png

  2. 數字轉字串
    https://ithelp.ithome.com.tw/upload/images/20261007/20184397qCUmv23hRQ.png

  • 參考教學影片:https://www.youtube.com/watch?v=KAj7gEgEE88&list=PL-g0fdC5RMbrKf_Co3mvz6YFbs9QOPvTf&index=5

*提醒邦友,使用第三方服務/API 時,請務必評估資安風險與隱私保護
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言